#include "file.h"
#include <QPixmap>
#include <QApplication>
#include <qapplication.h>
#include <qeventloop.h>
#include <QEventLoop>
#include <QWSServer>


QString fileSizeForHumanBeing(quint64 size)
{
	QString unit = "字节";
	quint64 size_tmp = size;
	

	if(size_tmp > 1024)
	{
		size_tmp /= 1024;
		unit = "kb";
	}
	if(size_tmp > 1024)
	{
		size_tmp /= 1024;
		unit = "M";
	}
	if(size_tmp > 1024)
	{
		size_tmp /= 1024;
		unit = "G";
	}
	

	return QString("%1%2").arg(size_tmp).arg(unit);

}
quint64 dirFileCount(const QString &path) 
{ 
#if 1
	quint64 count = 0; 
	
	QFileInfo info(path);

	if(info.isDir())
	{	
		QDirIterator iter(path, QDirIterator::Subdirectories);

		while (iter.hasNext()) {
			iter.next();
			
			QFileInfo info = iter.fileInfo();
			if (info.isFile()) {
			//	qDebug() << info.absoluteFilePath();
				count += 1;
			}
		}

		return count;
	}else {

		return 1;
	}


	
#else
	QDir dir(path); 
	quint64 size = 0; 
	
	//dir.entryInfoList(QDir::Files)返回文件信息 
	foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files)) 
	{ 
		//计算文件大小 
		size += 1; 
	} 
		
	foreach(QString subDir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) //dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot)返回所有子目录，并进行过滤 
	{ 
	
		size += dirFileCount(path + QDir::separator() + subDir);  //若存在子目录，则递归调用dirFileSize()函数 
	} 
	
	return size; 
#endif	
} 


quint64 dirFileSize(const QString &path) 
{ 
#if 0
	QDir dir(path); 
	quint64 size = 0; 
	
	//dir.entryInfoList(QDir::Files)返回文件信息 
	foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files)) 
	{ 
		//计算文件大小 
		size += fileInfo.size(); 
	} 
		
	foreach(QString subDir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) 			//dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot)返回所有子目录，并进行过滤 
	{ 
	
		size += dirFileSize(path + QDir::separator() + subDir);  					//若存在子目录，则递归调用dirFileSize()函数 
	} 
	
	return size; 
#else



	quint64 size = 0; 
	QFileInfo info(path);

	if(info.isDir())
	{	
		QDirIterator iter(path, QDirIterator::Subdirectories);

		while (iter.hasNext()) {
			iter.next();
			
			QFileInfo info = iter.fileInfo();
			if (info.isFile()) {
				size += info.size();
			}
		}
		
//		qDebug("return=%lld", size);
		return size;
	}else {
		 
		return info.size();
	}

#endif
} 

void GetFileInfoThread::SetMode(bool num)
{
	if(num == READ_FILE_COUNT)
	{
		mode = READ_FILE_COUNT;
	}else {
		mode = READ_FILE_SIZE;
	}
	

}

void GetFileInfoThread::ThreadStop()
{
	qDebug("thread stop");
	aliveFlag = false;

}


void GetFileInfoThread::SetFilePath(const QString & tmp)
{
	
	filePath = tmp;
	qDebug() << "set file path" << filePath;
}


GetFileInfoThread::GetFileInfoThread(QObject *parent) : QThread(parent) 
{
	aliveFlag = true;

	mode = READ_FILE_SIZE;
}
	
quint64 GetFileInfoThread::getCurFileSize(void)
{
//	qDebug("getCurFileSize=%lld", fileTotalSize);
	return fileTotalSize ;

}
quint64 GetFileInfoThread::getCurFileCount(void)
{
	return fileTotalCount;
}


void GetFileInfoThread::run()
{

	while(aliveFlag)
	{
		if(mode == READ_FILE_COUNT){
			fileTotalCount = dirFileCount(filePath);
		
		}else if(mode == READ_FILE_SIZE){
			fileTotalSize = dirFileSize(filePath);
		}

		 usleep(10000);
	}

	

	aliveFlag = true;



}















QString GetUserData::getdata()
{
	return dataEdit->text();

}


void GetUserData::createImConnect(QString ObjName)
{
    disconnect(im->keyboard, SIGNAL(setvalue(QString)), dataEdit, SLOT(setText(QString)));
   
    if(ObjName=="dataEdit")
        connect(im->keyboard, SIGNAL(setvalue(QString)), dataEdit, SLOT(setText(QString)));
   
}
void GetUserData::setMyTitle(QString title)
{
	titleLb->setText(title);
}


GetUserData::GetUserData(QWidget *parent) :  QDialog(parent)
{
	im = new InputMethod;

	enterBt  = new QPushButton(this);
	cancelBt = new QPushButton(this);
	dataEdit = new QLineEdit(this);
	titleLb  = new QLabel(this); 

	enterBt->setText(tr("确定"));
	cancelBt->setText(tr("取消"));
	
	dataEdit->installEventFilter(im);
    dataEdit->setObjectName("dataEdit");

	QGridLayout *pMainLayout = new QGridLayout(this);

	connect(im,SIGNAL(setImObjName(QString)),this,SLOT(createImConnect(QString)));
	connect(enterBt, SIGNAL(clicked()), this, SLOT(accept()));
	connect(cancelBt, SIGNAL(clicked()), this, SLOT(reject()));

	pMainLayout->addWidget(titleLb,		0,0,1,2);
	pMainLayout->addWidget(dataEdit,	1,0,1,2);
	pMainLayout->addWidget(enterBt,		2,0,1,1);
	pMainLayout->addWidget(cancelBt,	2,1,1,1);
	
	

	this->setWindowFlags(Qt::FramelessWindowHint);
	this->setLayout(pMainLayout);
}

GetUserData::~GetUserData()
{
	
}


#define WIDE 100
#define HIGH 50



Folder::Folder(QWidget *parent) :  QDialog(parent)
{
	QGridLayout *pMainLayout = new QGridLayout;
	
	process = new QProcess(this);
	process1 = new QProcess(this);
//	process->setReadChannel(QProcess::StandardOutput);
//	process->setProcessChannelMode(QProcess::MergedChannels); 
	
	thread = new GetFileInfoThread(this);
	timer = new QTimer(this);

//	::setvbuf(stdout, (char *)NULL, _IONBF, 0);
	totaltime = 0;
	speed = 0;

	pd = new QProgressDialog(tr("消息"),tr("取消"), 0, 50000, this);
	pd->setWindowTitle(tr("消息"));//设置标题
	pd->setWindowModality(Qt::WindowModal);//模态对话框
	pd->setStyleSheet("QLabel{qproperty-alignment: 'AlignVCenter | AlignLeft'};");
	pd->setFixedSize(500, 150);	
	pd->setRange(0, 100);
//	pd->setAutoClose(false);
//	pd->setAutoReset(false);

	removeBt = new QPushButton(this);
	cutBt = new QPushButton(this);
	copyBt = new QPushButton(this);
	pasteBt = new QPushButton(this);
	renameBt = new QPushButton(this);
	superrmBt = new QPushButton(this);
	mkdirBt = new QPushButton(this);
	exitBt  = new QPushButton(this);
	refreshBt = new QPushButton(this);
	infoBt = new QPushButton(this);


	removeBt->setFixedSize(WIDE, HIGH);
	cutBt->setFixedSize(WIDE, HIGH);
	copyBt->setFixedSize(WIDE, HIGH);
	pasteBt->setFixedSize(WIDE, HIGH);
	renameBt->setFixedSize(WIDE, HIGH);
	superrmBt->setFixedSize(WIDE, HIGH);
	mkdirBt->setFixedSize(WIDE, HIGH);
	exitBt->setFixedSize(WIDE, HIGH);
	refreshBt->setFixedSize(WIDE, HIGH);
	infoBt->setFixedSize(WIDE, HIGH);

	psplitter = new QSplitter();   //分割窗口类
	psplitter->setObjectName(QString::fromUtf8("splitter"));

	m_pos=0;
	QStringList filter;

	pdirModel=new QDirModel();
	pdirModel->setReadOnly(false); 
	pdirModel->setSorting(QDir::DirsFirst | QDir::IgnoreCase | QDir::Name); 

	removeBt->setText(tr("删除"));
	cutBt->setText(tr("剪切"));
	copyBt->setText(tr("复制"));
	pasteBt->setText(tr("粘贴"));
	renameBt->setText(tr("重命名"));
	superrmBt->setText(tr("指定删除"));
	mkdirBt->setText(tr("新建目录"));
	exitBt->setText(tr("退出"));
	refreshBt->setText(tr("刷新"));
	infoBt->setText(tr("属性"));

	ptreeView = new QTreeView(psplitter);//下拉浏览
	ptreeView->setObjectName(QString::fromUtf8("treeView"));
	ptreeView->setBackgroundRole(QPalette::Dark);
	ptreeView->setAutoFillBackground(true);
	ptreeView->setModel(pdirModel);
	//   ptreeView->setRootIndex(pdirModel->index(QDir::currentPath()));
	ptreeView->setRootIndex(pdirModel->index("/"));
	ptreeView->setAlternatingRowColors(true); 


	if(g_lcdsize == LCDSIZE_480x272)
	{
		ptreeView->setIconSize( QSize(15, 15) );
	}else{
		ptreeView->setIconSize( QSize(30, 30) ); //左边文件图标的大小
	}
	
	
	//	ptreeView->setColumnWidth(0, 400);
	ptreeView->setColumnHidden(3, true);
	ptreeView->setExpandsOnDoubleClick(true);
	ptreeView->setCurrentIndex(pdirModel->index("/root"));

	ptreeView->header()->setResizeMode(QHeaderView::ResizeToContents);   //自动适应列宽

	
	
//	connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOut()));
	connect(process, SIGNAL(readyRead()), this, SLOT(readOut()));
	connect(process, SIGNAL(finished(int)), this, SLOT(processFinish(int)));

	connect(removeBt, SIGNAL(clicked()), this, SLOT(removeClick()));
	connect(cutBt, SIGNAL(clicked()), this, SLOT(cutClick()));
	connect(copyBt, SIGNAL(clicked()), this, SLOT(copyClick()));
	connect(pasteBt, SIGNAL(clicked()), this, SLOT(pasteClick()));
	connect(superrmBt, SIGNAL(clicked()), this, SLOT(superrmClick()));
	connect(renameBt, SIGNAL(clicked()), this, SLOT(renameClick()));
	connect(mkdirBt, SIGNAL(clicked()), this, SLOT(mkdirClick()));
	connect(exitBt, SIGNAL(clicked()), this, SLOT(close()));
	connect(refreshBt, SIGNAL(clicked()), this, SLOT(refreshBtClick()));
	connect(infoBt, SIGNAL(clicked()), this, SLOT(infoBtClick()));
	
	connect(timer, SIGNAL(timeout()), this, SLOT(setDialogProcess()));
	connect(pd, SIGNAL(canceled()), this, SLOT(cancelTask()));
	
//	 pasteBt->setEnabled(false);
//	 pasteBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");


	 pMainLayout->addWidget(copyBt, 0, 6, 1, 1);
	 pMainLayout->addWidget(cutBt, 1, 6, 1, 1);
	 pMainLayout->addWidget(pasteBt, 2, 6, 1, 1);
	 pMainLayout->addWidget(removeBt, 3, 6, 1, 1);
	 pMainLayout->addWidget(superrmBt, 4, 6, 1, 1);
	 pMainLayout->addWidget(renameBt, 5, 6, 1, 1);
	 pMainLayout->addWidget(mkdirBt, 6, 6, 1, 1);
	 pMainLayout->addWidget(refreshBt, 7, 6, 1, 1);
	 pMainLayout->addWidget(infoBt, 8, 6, 1, 1);
	 pMainLayout->addWidget(exitBt, 9, 6, 1, 1);

	 

	pMainLayout->addWidget(ptreeView, 0, 0, 10, 5);
 
//	pMainLayout->setContentsMargins(40, 15, 40, 15);//设置左,上,右,下的空白

 
   this->setLayout(pMainLayout);


  


}



bool Folder::checkValid(void)
{
	quint64 destFreeSize;
	struct usb_mtd_info local_info;
	QFileInfo file_info;
	
	qDebug("check valid");

	WeiqianFunctions::get_free_space(destPath.toLocal8Bit().data(), &local_info);
	destFreeSize = local_info.free_size;

	qDebug("%s free %lld src=%lld", destPath.toLocal8Bit().data(), destFreeSize, fileSize);

#if 0
	if(destFreeSize > fileSize/1024)
	{
		file_info.setFile(destPath + "/" + srcFileName);
		
		if(file_info.exists() && !(srcPath == (destPath + "/" + srcFileName)))
		{

			
			if(QMessageBox::warning(NULL, "Warning", QString("[%1]已存在,确定覆盖吗?").arg(destPath + "/" + srcFileName), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
			{
				process->start(QString("rm %1  -r").arg(destPath + "/" + srcFileName));	 
				process->waitForFinished(-1);
				
				return true;
			}
		}else{
			return true;
		}
			
	}
#endif

#if 1

	file_info.setFile(destPath + "/" + srcFileName);

	if(file_info.exists())
	{
		if(srcPath == (destPath + "/" + srcFileName))
		{
			return true;
		}

		if(dirFileSize(destPath + "/" + srcFileName)+destFreeSize >  fileSize){   //防止同名覆盖时,源文件夹偷偷掺杂进一个大文件,虽然名字一样,但是会出问题,以已经拷进来的为准
			if(QMessageBox::warning(NULL, "Warning", QString("[%1]已存在,确定覆盖吗?").arg(destPath + "/" + srcFileName), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
			{
				process->start(QString("rm %1  -r").arg(destPath + "/" + srcFileName));	 
				process->waitForFinished(-1);
				
				return true;
			}
			
		}else{
			QMessageBox::critical(this, tr("错误"), QString("覆盖拷贝出错!目标空间不足 需求=%1 目标剩余=%2").arg(fileSize).arg(dirFileSize(destPath + "/" + srcFileName)+destFreeSize));
			return false;
		}


	}else if(destFreeSize > fileSize/1024)
	{
		return true;
	}







#endif
	if((fileSize/1024 >= destFreeSize))
	{
		QMessageBox::critical(this, tr("错误"), QString("目标空间不足,需求=%1M,但剩余=%2M").arg(fileSize/1024/1024).arg(destFreeSize/1024)); 
		
	}

	if(srcPath == (destPath + "/" + srcFileName))
	{
		
		QMessageBox::critical(this, tr("错误"), tr("原路径和目标路径相同!!!!")); 
	}

	return false;

}



void Folder::setDialogProcess()
{
	
	currSize = thread->getCurFileSize(); 

	
	percent = currSize*100 / fileSize;
	
	
//	qDebug("getchar=%c", getchar());
//	pd->setLabelText(process->readAllStandardOutput());


	
	pd->setValue(percent);
	
//	qDebug("getcur=%lld percent=%d pd->setValue=%d", currSize, percent, pd->value()); 

	totaltime += 100;   //ms
	
#if 1
	if(process->state() == QProcess::NotRunning)
	{
				 
		if(pd->value() == 100)
		{
			timer->stop();
			thread->ThreadStop();

			speed = fileSize/totaltime;   //  kb/ms = M/s
			qDebug("normal total time=%f  speed=%f kb/s", totaltime, speed);
			
			QMessageBox::information(this, "信息", QString("操作成功\n源文件大小=%1字节\n实际的大小=%2字节\n拷贝用时=%4秒\n平均速度=%3kb/s(%5M/s)").arg(fileSize).arg(dirFileSize(destPath + "/" + srcFileName)).arg(speed).arg(totaltime/1000).arg(QString::number(speed/1024, 'f', 2)));
			
	 	}else if(pd->value() == -1)  //假如拷贝小文件就会死的很快,返回-1;我也不知道为什么;
	 	{
	// 		qDebug("return -1");
			timer->stop();
			thread->ThreadStop();
			pd->close();

			speed = fileSize/totaltime;		//  kb/ms = M/s
			qDebug("special total time=%f  speed=%f kb/s", totaltime, speed);
			
			QMessageBox::information(this, "信息", QString("操作成功\n源文件大小=%1字节\n实际的大小=%2字节\n拷贝用时=%4秒\n平均速度=%3kb/s(%5M/s)").arg(fileSize).arg(dirFileSize(destPath + "/" + srcFileName)).arg(speed).arg(totaltime/1000).arg(QString::number(speed/1024, 'f', 2)));
	 	}

		
	 	refreshBtClick();
	}
#endif
}

void Folder::infoBtClick(void)
{
	QString name = pdirModel->fileInfo(ptreeView->currentIndex()).fileName();
	QString type = pdirModel->fileInfo(ptreeView->currentIndex()).isDir() ? "目录":"普通文件";
	quint64 size = dirFileSize(pdirModel->filePath(ptreeView->currentIndex())) ;
	QString unit = "字节";
	quint64 size_tmp = size;

	struct usb_mtd_info local_info;

	WeiqianFunctions::get_free_space(pdirModel->filePath(ptreeView->currentIndex()).toLocal8Bit().data(), &local_info);


	if(size_tmp > 1024)
	{
		size_tmp /= 1024;
		unit = "kb";
	}
	if(size_tmp > 1024)
	{
		size_tmp /= 1024;
		unit = "M";
	}
	if(size_tmp > 1024)
	{
		size_tmp /= 1024;
		unit = "G";
	}

	if(name == "usrfs"){ 
		QMessageBox::information(this, tr("属性"), QString("名称: %1\n类型: %2\n总容量: %3\n已用容量: %4\n剩余容量: %5").arg(name).arg(type).arg(fileSizeForHumanBeing((local_info.total_size)*1000)).arg(fileSizeForHumanBeing(size)).arg(fileSizeForHumanBeing((local_info.total_size)*1000 - size)));
	}else{
		QMessageBox::information(this, tr("属性"), QString("名称: %1\n类型: %2\n大小: %3字节\n           %4 %5").arg(name).arg(type).arg(size).arg(size_tmp).arg(unit)); 
	}
}


void Folder::refreshBtClick(void)
{
	process1->start("sync &");	 
	process1->waitForFinished(-1);
	pdirModel->refresh();
}


void Folder::readOut()
{
	QString tmp;

	qDebug("readout");

	while(!process->atEnd())
	{
		 
		tmp = process->readLine();
//		qDebug() << "[read]" << tmp;
//		pd->setLabelText(tmp);
	
	}

}

void Folder::processFinish(int state)
{
	QString tmp;

	
	 
//	tmp = process->readAll();
	qDebug() << "process finish";
//	pd->setLabelText(tmp);
//	timer->stop();
//	thread->ThreadStop();

}


bool Folder::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist)  
{  
    toDir.replace("\\","/");  
    if (sourceDir == toDir){  
        return true;  
    }  
    if (!QFile::exists(sourceDir)){  
        return false;  
    }  
    QDir *createfile     = new QDir;  
    bool exist = createfile->exists(toDir);  
    if (exist){  
        if(coverFileIfExist){  
            createfile->remove(toDir);  
        }  
    }//end if  

  	pd->setLabelText(QString("%1 -> %2").arg(sourceDir).arg(sourceDir));
    if(!QFile::copy(sourceDir, sourceDir))  
    {  
        return false;  
    }  
    return true;  
}  
  
//拷贝文件夹：  
bool Folder::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)  
{  
    QDir sourceDir(fromDir);  
    QDir targetDir(toDir);  
    if(!targetDir.exists()){    /**< 如果目标目录不存在，则进行创建 */  
        if(!targetDir.mkdir(targetDir.absolutePath()))  
            return false;  
    }  
  
    QFileInfoList fileInfoList = sourceDir.entryInfoList();  
    foreach(QFileInfo fileInfo, fileInfoList){  
        if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")  
            continue;  
  
        if(fileInfo.isDir()){    /**< 当为目录时，递归的进行copy */  
            if(!copyDirectoryFiles(fileInfo.filePath(),   
                targetDir.filePath(fileInfo.fileName()),  
                coverFileIfExist))  
                return false;  
        }  
        else{            /**< 当允许覆盖操作时，将旧文件进行删除操作 */  
            if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){  
                targetDir.remove(fileInfo.fileName());   
            }  

            pd->setLabelText(QString("%1 -> %2").arg(fileInfo.filePath()).arg(targetDir.filePath(fileInfo.fileName())));
  
            /// 进行文件copy  
            if(!QFile::copy(fileInfo.filePath(),  targetDir.filePath(fileInfo.fileName()))){  
                    return false;  
            }  
        }  
    }  
    return true;  
}  






void Folder::superrmClick(void)
{

	qDebug("super remove");

	GetUserData tmp;
	tmp.setMyTitle("请输入要删除目标的 [绝对路径]:");

	if(tmp.exec() == QDialog::Accepted)
	{
		QString dirName  = tmp.getdata();

		QFileInfo info(dirName);

		if(!info.exists())
		{
			QMessageBox::critical(this, tr("错误"), tr("***没有这个文件或者目录")); 
			return;
		}

		if(dirName == "/")
		{
			QMessageBox::critical(this, tr("错误"), tr("***系统敏感目录不能删除")); 
			return;
		}	
		  
		if(QMessageBox::warning(NULL, "Warning", QString("确定删除[%1]吗").arg(dirName), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No)
		{
			return;
		}	
		

		process->start(QString("rm %1  -rf").arg(dirName));
			 
		process->waitForFinished(-1);

		pdirModel->refresh();
	}
}

void Folder::copyClick(void)
{
	totaltime = 0;
	speed = 0;
	
	cmd.clear();
	srcPath.clear();
	srcFileName.clear();
	
	
	srcPath = pdirModel->filePath(ptreeView->currentIndex());
	srcFileName = pdirModel->fileInfo(ptreeView->currentIndex()).fileName();


	if(srcFileName.contains(' '))
		qDebug("该文件含有空格符");

	fileSize  = dirFileSize(srcPath);
	fileCount = dirFileCount(srcPath);
	
	
	cmd = "cp";

//	pasteBt->setEnabled(true);
//	pasteBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");

	qDebug("copyClick srcfilepath=%s count=%lld ", srcPath.toLocal8Bit().data(), fileCount);


}
void Folder::cutClick(void)
{
	totaltime = 0;
	speed = 0;

	cmd.clear();
	srcPath.clear();
	srcFileName.clear();
	cmd = "mv";
	
	srcPath = pdirModel->filePath(ptreeView->currentIndex());
	srcFileName = pdirModel->fileInfo(ptreeView->currentIndex()).fileName();

	fileSize  = dirFileSize(srcPath);
	fileCount = dirFileCount(srcPath);

//	pasteBt->setEnabled(true);
//	pasteBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");

	qDebug("cutClick srcfilepath=%s count=%lld ", srcPath.toLocal8Bit().data(), fileCount);


	
}
void Folder::pasteClick(void)
{
	qDebug("pasteClick");

//	process->close();
	totaltime = 0;
	speed = 0;

	destPath = pdirModel->filePath(ptreeView->currentIndex());

	if(checkValid() == false)
			return;

		
	thread->SetFilePath(destPath + "/" + srcFileName);
	
	qDebug() << "destfullPath" << destPath + "/" + srcFileName;

	if(cmd.contains("cp"))
	{
		qDebug("use cp");
		pd->setLabelText(tr("正在复制..."));//设置标题
		setButton(false);

		process->start(QString("%1 %2 %3 -r -v").arg(cmd).arg(srcPath).arg(destPath));
		process->waitForStarted(2000);




	}else{
		qDebug("use mv");

		pd->setLabelText(tr("正在移动..."));
		setButton(false);
		process->start(QString("%1 %2 %3").arg(cmd).arg(srcPath).arg(destPath));
	}

	pd->show();
	thread->start();
	timer->start(100);
	
//	pasteBt->setEnabled(false);
//	pasteBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");

	refreshBtClick();

	
	qDebug("finish cursize=%lld total=%lld", currSize, fileSize);
	qDebug("cmd=%s", QString("%1 %2 %3 -r -v").arg(cmd).arg(srcPath).arg(destPath).toLocal8Bit().data());
}

void Folder::mkdirClick() 
{ 
        QModelIndex index = ptreeView->currentIndex(); 
        if (!index.isValid()) { 
                return; 
        }

#if 0        
        QString dirName = QInputDialog::getText(this, tr("Create Directory"),  tr("Directory name")); 
        if (!dirName.isEmpty()) { 
                if (!pdirModel->mkdir(index, dirName).isValid()) { 
                        QMessageBox::information(this, tr("Create Directory"), tr("Failed to create the directory")); 
                } 
        } 
#endif


	GetUserData tmp;
	tmp.setMyTitle("请输入名字:");

	if(tmp.exec() == QDialog::Accepted)
	{
		qDebug("appect");
		QString dirName  = tmp.getdata();

		if (!dirName.isEmpty()) { 
			if (!pdirModel->mkdir(index, dirName).isValid()) { 
				QMessageBox::critical(this, tr("Create Directory"), tr("***创建文件夹失败!!!")); 
			} else{
				QMessageBox::information(this, tr("Create Directory"), QString("创建文件夹 [%1] 成功").arg(dirName)); 
			}
		}

		
	}
}

void Folder::removeClick(void)
{
	qDebug("removeClick");
	

#if 1	
	QModelIndex index = ptreeView->currentIndex();
	if (!index.isValid()) {
			return;
	}

	QMessageBox::StandardButton rb = QMessageBox::warning(NULL, "Warning", QString("确定删除[%1]吗").arg(pdirModel->filePath(ptreeView->currentIndex())), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
	if(rb == QMessageBox::No)
	{
		return;
	}

#if 0	
	if (pdirModel->fileInfo(index).isDir()) {
			ok = pdirModel->rmdir(index);
	} else {
			ok = pdirModel->remove(index);
	}
#endif

	
		
	process->start(QString("rm %1  -r").arg(pdirModel->filePath(ptreeView->currentIndex())));
		 
	process->waitForFinished(-1);

	pdirModel->refresh();

//	cmd.clear();
//	srcPath.clear();
//	srcFileName.clear();

#else
	QFileInfo info(srcPath);


	if(info.isFile())
	{
		qDebug("it's file");
		ok = QFile::remove(srcPath);
	}else if(info.isDir()){
		qDebug("it's dir");
		QDir dir(srcPath);
		
		ok = dir.rmdir(srcPath);
	}





	if (!ok) {
		QMessageBox::information(this, tr("Remove"),tr("Failed to remove %1").arg(srcPath));
	}else{
		QMessageBox::information(this, tr("Remove"),tr("删除%1成功").arg(srcPath));
	}
#endif

}
void Folder::renameClick(void)
{
	qDebug("renameClick");
	QString rename;
	QString file;
	QFileInfo info = pdirModel->fileInfo(ptreeView->currentIndex());
	QString curPath = pdirModel->filePath(ptreeView->currentIndex());	

	GetUserData tmp;
	tmp.setMyTitle("请输入名字:");

	if(tmp.exec() == QDialog::Accepted)
	{
		qDebug("appect");
		rename = tmp.getdata();

		QMessageBox::StandardButton rb = QMessageBox::warning(NULL, "Warning", QString("确定把 %1 重命名为 %2 吗?").arg(info.fileName()).arg(rename), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
		if(rb == QMessageBox::No)
		{
			tmp.close();
			return;
		}

		if(info.isDir())
		{
			QDir dir(curPath);
			if(dir.rename(curPath, info.dir().absolutePath().append("/").append(rename)) == false)
				QMessageBox::warning(NULL, "Warning", "重命名目录失败");
	
		}else{
			qDebug() << info.dir().absolutePath();
			qDebug() << info.dir().absolutePath().append(rename);

			
			if(QFile::rename(curPath, info.dir().absolutePath().append("/").append(rename)) == false)
				QMessageBox::warning(NULL, "Warning", "重命名文件失败");
		}

		pdirModel->refresh();
	}else{
		qDebug("reject");
	}


	
	tmp.close();
	
}


void Folder::setButton(bool enable)
{
	if(enable)
	{
		removeBt->setEnabled(true);
	    cutBt->setEnabled(true);
	    copyBt->setEnabled(true);
	    pasteBt->setEnabled(true);
	    renameBt->setEnabled(true);
	    superrmBt->setEnabled(true);
	    mkdirBt->setEnabled(true);
	    exitBt->setEnabled(true);
	    refreshBt->setEnabled(true);
	    infoBt->setEnabled(true);
		
		removeBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	    cutBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	    copyBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	    pasteBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	    renameBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	    superrmBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	    mkdirBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	    exitBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	    refreshBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	    infoBt->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	}else{

		removeBt->setEnabled(false);
		cutBt->setEnabled(false);
		copyBt->setEnabled(false);
		pasteBt->setEnabled(false);
		renameBt->setEnabled(false);
		superrmBt->setEnabled(false);
		mkdirBt->setEnabled(false);
		exitBt->setEnabled(false);
		refreshBt->setEnabled(false);
		infoBt->setEnabled(false);

		removeBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
		cutBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
		copyBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
		pasteBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
		renameBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
		superrmBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
		mkdirBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
		exitBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
		refreshBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
		infoBt->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
	}


}


void Folder::cancelTask()
{
	process->kill();
	timer->stop();
	thread->ThreadStop();
	pd->cancel();
//	pd->close();


//	QMessageBox::warning(NULL, "Warning", "已取消拷贝,请手动删除");
	setButton(true);
	pdirModel->refresh();
}

Folder::~Folder()
{

	qDebug("file stop");
	process1->start("sync &");	 
	process1->waitForFinished(-1);

	thread->ThreadStop();
}


